<?php
	class PartnerAction extends BaseAction{
		public function index() {
			$parent_id = $_REQUEST['parent_id'];
			$enable = $_REQUEST['enable'];
			$sort_id = $_REQUEST['sort_id'];
			if(empty($enable)){
				$enable='all';
			}
			
			$map = ' 1=1 ';
			if(!empty($parent_id)){
				$map= $map.' and ( id='.$parent_id.' or parent_id='.$parent_id.' ) ';
			}
			if(!empty($sort_id)){
				$map= $map." and ( sort_id='".$sort_id."' ) ";
			}
				
			if($enable!='all'){
				$map= $map." and enable='".$enable."' ";
			}

			$pagedata = D('Partner')->selectAllByPage($map);
			$this->assignRequestParams();
			$this->assign('pagedata', $pagedata);
			$this->display();
		}
	
	
		public function addPartner() {
			$this->display('edit');
		}
	
		
		public function doAddPartner() {
			$map['title'] = $_POST['title'];
			$map['sort_id'] = $_POST['sort_id'];
			$map['homepage'] = $_POST['homepage'];
			$map['contact'] = $_POST['contact'];
			
			$map['phone'] = $_POST['phone'];
			$map['mobile'] = $_POST['mobile'];
			$map['address'] = $_POST['address'];
			$map['zipcode'] = $_POST['zipcode'];
			$map['location'] = $_POST['location'];
			$map['parent_id'] = intval($_POST['parent_id']);
			$map['enable'] 	=	$_POST['enable']=="Y"?'Y':'N';
			$map['admin_password'] = md5("111111");
			$map['checker_password'] = '';
			$map['popular_area'] = $_POST['popular_area'];
			$map['brief'] = t($_POST['brief']);
			$map['tag']=t($_POST['tag']);
			//$map['story'] = stripslashes($_POST['story']);
			
			$gparea = explode(',',$_POST['gparea']);
		    if(!empty($gparea[0])) {
		    		$map['province_id'] 	=	intval($gparea[0]);
		     		$map['city_id'] 	=	intval($gparea[1]);
		     		$map['area_id'] 	=	intval($gparea[2]);
		    }
		    $map['ctime'] 	=	time();
		    $map['open'] 	=	'Y';
		    $map['display'] 	=	'Y';
		    $map['insert_admin_id'] 	=	$this->adminId;
		    $map['brand_icon'] = 'system/default_partner_logo.jpg';
		    $map['intro_imgpath1'] = 'system/default_partner_intro.jpg';
		    $Partner = D('Partner');
		    $id = $Partner->add($map);
		    $map['id']=$id;
		    if(!empty($id))$this->addPopularArea($map,array('title'=>$map['tag']));
		    unset($map);
		    if(!empty($id)){
		    	$options =	array();
			 	$options['userId']			=	$this->adminId;
				$options['allow_exts']	=	'jpg,gif,jpeg,bmp';
				$options['custom_path'] = 'partner/'.$id.'/';
				$options['save_path']	=	UPLOAD_PATH.'/'.$options['custom_path'];
				
			  	$info	=	X('Xattach')->upload('partner',$options);
				
				if($info['status']) {
						$map['brand_icon'] = $info['info'][0]['savepath'].$info['info'][0]['savename'];
						$map['id'] = $id;
						$Partner->save($map);
				}else{
				}
				
				$this->assign('jumpUrl',U('/Partner/index'));
				$this->success('新增成功！');
			}else{
				
			}
			$this->error('新增失败！');
		}
	
		public function editPartner() {
			$id = $_GET['id'];
			if(empty($id))$this->error('参数错误！');
			$partner = M('Partner')->where('id='.$_GET['id'])->find();
			if(empty($partner))$this->error('商户不存在！');
			$this->assign('type', 'edit');
			$this->assign('partner', $partner);
			$this->display('edit');
		}
	
		public function doEditPartner() {
			$id = $_POST['id'];
			if(empty($id))$this->error('参数错误！');
			$map['id'] = $id;
			$map['title'] = $_POST['title'];
			$map['sort_id'] = $_POST['sort_id'];
			$map['homepage'] = $_POST['homepage'];
			$map['contact'] = $_POST['contact'];
			
			$map['phone'] = $_POST['phone'];
			$map['mobile'] = $_POST['mobile'];
			$map['address'] = $_POST['address'];
			$map['zipcode'] = $_POST['zipcode'];
			$map['location'] = $_POST['location'];
			$map['parent_id'] = intval($_POST['parent_id']);
			$map['enable'] 	=	$_POST['enable']=="Y"?'Y':'N';
			$map['popular_area'] = $_POST['popular_area'];
			$map['brief'] = t($_POST['brief']);
			$map['tag'] = t($_POST['tag']);
			//$map['story'] = stripslashes($_POST['story']);
			
			$gparea = explode(',',$_POST['gparea']);
			if($id==$map['parent_id']){
					$this->error('不能将商户本身设为上级商户！');
			}
		    if(!empty($gparea[0])) {
		    		$map['province_id'] 	=	intval($gparea[0]);
		     		$map['city_id'] 	=	intval($gparea[1]);
		     		$map['area_id'] 	=	intval($gparea[2]);
		    }
		    $map['mtime'] 	=	time();
		    $map['modify_admin_id'] 	=	$this->adminId;
		    $Partner = D('Partner');
		   	$Partner->save($map);
		   	$this->_refreshItemSum($map['tag']);
		    unset($map);
		    if(!empty($id)){
		    	$options =	array();
			 	$options['userId']			=	$this->adminId;
				$options['allow_exts']	=	'jpg,gif,jpeg,bmp';
				$options['custom_path'] = 'partner/'.$id.'/';
				$options['save_path']	=	UPLOAD_PATH.'/'.$options['custom_path'];
				
			  	$info	=	X('Xattach')->upload('partner',$options);
				
				if($info['status']) {
						$map['brand_icon'] = $info['info'][0]['savepath'].$info['info'][0]['savename'];
						$map['id'] = $id;
						$Partner->save($map);
				}else{
				}
				
				$this->assign('jumpUrl',U('/Partner/editPartner',array('id'=>$id)));
				$this->success('修改成功！');
			}else{
				
			}
			$this->error('修改失败！');
		}
	
		
		public function doDeletePartner() {
			$_POST['ids']	= explode(',', t($_POST['ids']));
			if (empty($_POST['ids'])) {
				echo 0;
				return ;
			}
			//$map['id']	= array('in', $_POST['ids']);
			$partner = D('Partner')->where(array('id'=>$_POST['ids']))->find();
			$result = D('Partner')->deleteByIds($_POST['ids']) ? '1' : '0';
			$this->_refreshItemSum($partner['tag']);
			echo $result;
		}
	
		
		public function getJson(){
			$searchtext = $_REQUEST['searchtext'];
			$level = intval($_REQUEST['level']);//设置只能选择几级商户 level=1为选择一级商户，其他随便选择
			$ignoreId = intval($_REQUEST['ignoreId']);//设置忽略的商户
			$map = " 1=1 ";
			if(!empty($searchtext)){
				$map=$map." and title like '%".$searchtext."%' ";
			}
			if(!empty($ignoreId)){
				$map=$map." and id!=".$ignoreId.' ';
			}
			//echo $map.'  '.$level;
			if($level==1)$listpartner = D('Partner')->selectMainPartners($map,100);
			else $listpartner = D('Partner')->selectAllByPage($map,20);
			exit(json_encode($listpartner['data'])); 
		}
		
		
		public function infoEdit(){
			$partnerId = $_REQUEST['partner_id'];
			$content = stripslashes($_POST['content']);
			$explain = stripslashes($_POST['explain']);
			$partner = D('Partner')->selectById($partnerId);
			if(empty($partner))$this->error('商户不存在！');
			
			$story = M('PartnerInfo')->where('partner_id='.$partnerId)->find();
			//如果$content不为空,则为要保存数据.判断$story是否为空来进行添加或修改操作
			if(!empty($content)&&!empty($explain)){
				$map['partner_id'] = $partnerId;
				$map['content'] = $content;
				$map['explain'] = $explain;
				if(empty($story)){
					M('PartnerInfo')->add($map);
				}else{
					$map['id'] = $story['id'];
					M('PartnerInfo')->save($map);
				}
				$story = M('PartnerInfo')->where('partner_id='.$partnerId)->find();
				$this->assign('result','保存成功！');
			}
			$this->assign('partner',$partner);
			$this->assign('story',$story);
			$this->display();
		}
		
		
	public function locationEdit(){
			$partnerId = $_REQUEST['partner_id'];
			$location = stripslashes($_POST['location']);
			$partner = D('Partner')->selectById($partnerId);
			if(empty($partner))$this->error('商户不存在！');
			
			//如果$content不为空,则为要保存数据.判断$story是否为空来进行添加或修改操作
			if(!empty($location)){
				$map['id'] = $partnerId;
				$map['location'] = $location;
				M('Partner')->save($map);
				$partner = D('Partner')->selectById($partnerId);
				$this->assign('result','保存成功！');
			}
			$this->assign('partner',$partner);
			$this->display();
		}
		
		
		public function imgEdit(){
			$id = $_GET['id'];
			$type = $_GET['type'];
			$newimgpath = $_POST['newimgpath'];
			if(!empty($newimgpath)){
				$result['status']=0;
				if(empty($id))exit(json_encode($result)); 
				if(empty($type))exit(json_encode($result)); 
				$map['id']=$id;
				if($type=='logo')$map['brand_icon']=$newimgpath;
				if($type=='intro1')$map['intro_imgpath1']=$newimgpath;
				if(empty($map['brand_icon'])&&empty($map['intro_imgpath1']))exit(json_encode($result));
				$no = M('Partner')->save($map);
				if($no)$result['status']=1;
				exit(json_encode($result));
			}
			if(empty($id))$this->error('参数错误！');
			$partner = M('Partner')->where('id='.$_GET['id'])->find();
			if(empty($partner))$this->error('商户不存在！');
			$this->assign('partner', $partner);
			$this->display();
		}
		
		
		public function domodifypwd(){
			$partner_id		= t($_POST['partner_id']);
			$mpwd_opt 		= t($_POST['mpwd_opt']);
			$adminnewpwd 	= t($_POST['adminnewpwd']);
			$checkernewpwd 	= t($_POST['checkernewpwd']);
			
			if( !in_array($mpwd_opt,array('admin','checker','nopwd')) )	$this->error('修改失败，未指定修改类型！');
			if($mpwd_opt=='admin'&&empty($adminnewpwd))	$this->error('修改失败，新管理员密码为空！');
			if($mpwd_opt=='checker'&&empty($checkernewpwd))	$this->error('修改失败，新验证员密码为空！');
		
			$partner = D('Partner','Admin')->selectById($partner_id);
			
			if(empty($partner)) {
				$this->error('修改失败，店铺不存在！');
			}
			if($mpwd_opt=='admin'){
				if(md5($adminnewpwd)==$partner['admin_password']){
					
				}else{
					$map['id']=$partner_id;
					$no = M('Partner')->where($map)->setField('admin_password', md5($adminnewpwd));
					if(!$no)$this->error('管理员密码修改失败！');
				}
				$this->success('管理员密码修改成功！新密码：'.$adminnewpwd);
			}
			
			if($mpwd_opt=='checker'){
				if(md5($checkernewpwd)==$partner['checker_password']){
					
				}else{
					$map['id']=$partner_id;
					$no = M('Partner')->where($map)->setField('checker_password', md5($checkernewpwd));
					if(!$no)$this->error('验证员密码修改失败！');
				}
				$this->success('验证员密码修改成功！新密码：'.$checkernewpwd);
			}
			
			
			if($mpwd_opt=='nopwd'){
				if(empty($partner['checker_password'])){
					
				}else{
					$map['id']=$partner_id;
					$no = M('Partner')->where($map)->setField('checker_password', '');
					if(!$no)$this->error('验证员密码修改失败！');
				}
				$this->success('验证员设置为无需密码登录！');
			}
			$this->error('修改失败！');
		}
	
		
		/**
		 * 登录商户管理系统
		 */
		public function loginSHSystem(){
			$id = $_GET['partner_id'];
			service('Passport')->loginPartner($id,'admin', false);
			redirect(U('shanghu://Index/index'));
		}
		
		//添加地点
		function addPopularArea($partner,$popular){
			foreach($partner as $vo){
				if($vo['tag']==null){$vo['tag']='';}
				$tmp_tag = str_replace($popular['title'].",","",$vo['tag']);
				$tmp_tag = str_replace($popular['title'],"",$tmp_tag);
				$tmp_tag = $popular['title'].",".$tmp_tag;
				$tmp_tag = str_replace(",,,",",",$tmp_tag);
				$tmp_tag = str_replace(",,",",",$tmp_tag);
				//echo "<br>id=".$vo['id']."  tag=".$tmp_tag;
				M('Partner')->where(array('id'=>$vo['id']))->save(array('tag'=>$tmp_tag));
				$this->_refreshItemSum($vo['tag']);
			}
		}
		
		/** 更新店铺总数 **/
		private function _refreshItemSum($tag){
			$tag = str_replace(",","",$tag);
			if(empty($tag)||$tag=='')return;
			$map['title'] = $tag;
			$popular = model('AreaPopular')->where($map)->find();
			
			
			$partnerDao = M('Partner');
			$where['tag'] = array('like',"%".$tag.",%");
			$sum = $partnerDao->where($where)->count();
			
			$popular['item_sum']=$sum;
			model('AreaPopular')->save($popular);
		}
	}
?>